define(function(require, exports, module) {
    var router = require("router");
    //var app = require("app");
    var controller = {};
    controller.vue = function() {
        controller.vm = new Vue({
            router: router,
            data: function() {
                return {
                  
                  data: {
                    freight:{},
                    list:[],
                    shop_info:{},
                    type:0
                  },
                  loading: 0,
                  frisload:1,
                  address:{},
                  use_yie:0,
                  disabled:0,
                  location_info: '',
                  shop_id:0,
                  card_code:'',
                  order_amount:0,
                  multiArray: [],
                  user_info: {},
                  delivery_types: [],
                  delivery_type:'送货上门',
                  delivery_time:['尽快送达','2小时内'],
                  delivery_coverage:0,
                  card_title:'',
                  isWeiXin:0,
                };
            },
            el: '#pageCheckout',
            created: function() {
                this.fetchData();
            },
             mounted: function() {
                    
                    if (this.mounted == 1) {
                        return;
                    }
                    // this.bindPick();
                    var that = this ;
                this.mounted = 1;
            },


            methods: {
                fetchData: function() {
                    var _this = this;
                    this.shop_id=this.$route.params.shop_id;
                     this.isWeiXin =  app.isWeiXin();
                    this.getInfo();
                    
                },


                bindPick:function(){
                   var that = this ;
                   // console.log(that.multiArray[0]);

                   if(that.multiArray && that.multiArray.length>0){
                      app.picker("#chooseDeliveryType",{
                      title: "选择配送时间",
                      cols: [
                        {
                              textAlign: 'center',
                              values: that.multiArray[0]
                          },
                          {
                              textAlign: 'center',
                              values: that.multiArray[1]
                          },
                          {
                              textAlign: 'center',
                              values: that.multiArray[2]
                          }
                      ],
                      onClose: function(p) {
                           // console.log( p);
                            var v = p.displayValue;
                            // console.log(v);
                            that.bindChange(v);
                      },
                    });
                      // $("#chooseDeliveryType").picker();
                   }
                  
                  // console.log($("#bindChangeCeliveryC"));
                  if(that.delivery_types && that.delivery_types.length>0){
                    app.picker("#bindChangeCeliveryC",{
                          title: "选择配送方式",
                          cols: [
                       
                              {
                                  textAlign: 'center',
                                  values: that.delivery_types
                              }
                          ],
                          onClose: function(p) {
                               var v = p.displayValue;
                             
                               that.bindChangeCeliveryC(v);
                              // that.bindChange(p, v, dv);
                          },
                      });
                      // $("#bindChangeCeliveryC").picker();
                  }
                },

                   //选择配送公司
                bindChangeCeliveryC: function (value) {
                  // var value = e.detail.value;
                  // console.log(value);
                  // console.log(this.delivery_types);
                  this.setData({
                     delivery_type: value.join("")
                  });
                  this.loadCart(1);
                },
                 //选择时间
                bindChange:function(dv){
                  //console.log(e.detail.value);
                  // var value = e.detail.value;
                  if (dv[1] > dv[2] && (dv[2] > "04:00"||  dv[1] < "04:00")){
                    app.alert("您选择的时间段有误，请重新选择");
                    return ; 
                  }
                  this.delivery_time = dv;
                  console.log(this.delivery_time);
                  // this.setData({ delivery_time:dv});
                  // console.log(this.delivery_time);
                  if(this.card_code){
                     this.loadCart(1);
                  }
                },
                getInfo: function () {
                  var that = this;
                  app.get("api/user/info", {
                    fields: "avatarUrl,user_id,last_update_time,nickname"
                  }, function (res) {

                    if (res.code != 200) {
                      app.alert(res.msg);
                      return;
                    }
                 
                    that.setData({user_info: res.data });
               
                  });
                },

                // 检查配送范围
                checkDistance:function(){
                    var that = this;
                  if(!app.isWeiXin()){
                     return true;
                   }
                   if(!that.data.freight || !that.data.freight.delivery_coverage){
                    return true;
                   }
                   if(! that.location_info.latitude){
                     app.alert("请选择地址理位置");
                   }
                  
                    if ( that.location_info.latitude) {
                        var s = that.getDistance(that.location_info.longitude, that.location_info.latitude, that.data.shop_info.longitude, that.data.shop_info.latitude);
                        if (s > that.data.freight.delivery_coverage) {
                          app.alert("配送范围：" + that.data.freight.delivery_coverage + "公里，您当前超出配送范围");
                          return false;
                        }
                    }
                    return true;
                },

                chooseLocation:function(){
                  if(!app.isWeiXin()){
                     return ;
                   }
                  var that = this;
                  app.wxJs(function(wx) {
                      wx.getLocation({
                        cancel: function (res) {
                           app.alert("系统未能获取您的位置");
                        },
                        success: function (res) {
                          console.log("success", res);
                          if (!(res.longitude && res.latitude)) {
                            return;
                          }
                          res.latitude = res.latitude.toFixed(5);
                          res.longitude = res.longitude.toFixed(5);
                          
                          that.setData({ location_info: res });
                        }
                      });
                  });
              },
                  //计算两坐标的距离
              getDistance(lng1, lat1, lng2, lat2) {
                var radLat1 = lat1 * Math.PI / 180.0;
                var radLat2 = lat2 * Math.PI / 180.0;
                var a = radLat1 - radLat2;
                var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
                var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
                  Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
                s = s * 6378.137;// EARTH_RADIUS;
                s = Math.round(s * 10000) / 10000;
                return s;
              },

              //打开商家所在地点
              openlocation:function(){
                if(!app.isWeiXin()){
                     return ;
                   }
                 var that = this;
                  app.wxJs(function(wx) {
                      wx.openLocation({
                        latitude: Number(that.data.shop_info.latitude),
                        longitude: Number(that.data.shop_info.longitude),
                        scale: 28,
                        address: that.data.shop_info.fulladdress,
                        name: that.data.shop_info.name,
                      });
                });
              },


             
                setData:function(arr){
                  for( var i in arr){
                    // console.log(i);
                    // console.log(arr[i]);
                     // this.$set(i,arr[i]); 
                     this[i] = arr[i];
                  }
                },
              //加载购物车
                loadCart(reload = 0) {
                  var that = this;
                  if (reload == 1) {
                    this.setData({
                      loading: 0,
                      listData: [],
                    });
                  }
                  this.loading = 1;
                  app.get("mall/cart/getcartByUserId", {
                    shop_id: this.shop_id,
                    card_code: this.card_code,
                    delivery_type: this.delivery_type,
                    deliver_time: this.delivery_time.join(",")
                  }, function (res) {
                    that.loading = 0;
                    if (res.code != 200) {
                      app.alert(res.msg);
                      return;
                    }
                    that.frisload = 0;
                    // 卡券不可用
                    if (res.data.cardRes && res.data.cardRes.code>0){
                      app.alert(res.data.cardRes.msg);
                      that.card_code="";
                      that.card_title="";
                    }
                    //配送时间设置，及配送方式
                    that.setData({
                      data: res.data,
                      multiArray: res.data.select_delivery_min_max_time,
                      delivery_types: res.data.delivery_type,
                    });
                    // 配送范畴
                    if (res.data.freight && res.data.freight.delivery_coverage){
                      that.setData({
                         delivery_coverage: res.data.freight.delivery_coverage
                      });
                    }
                    // 配送可达时间
                    if (res.data.freight && res.data.freight.EstimatedTimeOfArrival && that.frisload==1) {
                      that.setData({
                        delivery_time: ['尽快送达', res.data.freight.EstimatedTimeOfArrival + '小时内']
                      });
                    }
                    // 默认地址
                    if(res.data.address){
                       that.address=res.data.address;
                    }
                     // console.log(that.multiArray);
                     // 选择时间插件
                     Vue.nextTick(function(){
                      that.bindPick();
                     });
                     
                  });
                },
                  /**
                 * 生命周期函数--监听页面显示
                 */
                pageShow: function () {
                  // console.log("23123");
                  var reload = app.getPageData("checkout/index",'reload');
                  var address = app.getPageData("address", 'address');

                  if (reload==1){
                    app.setPageData("checkout/index", { reload:0});
                    this.loadCart(1);
                  }
                   
                  if(address){
                    this.address=address;
                  }

                  this.loadCart();

                },
                suc:function(){
                 
                },
                //生成订单
                formSubmit:function(e){
                   
                  
                  var that = this;
                  that.setData({ loading: 1, disabled: 1 });
                  that.payloading = 1;
                  if (!this.address.telNumber && this.data.type===0){
                     app.alert("请选择收货地址");
                     that.setData({ loading: 0, disabled: 0 });
                     return false;
                  }
                  // console.log(this.delivery_type);
                  // 微信中可以计算配送距离
                  // if (!this.checkDistance()) {
                  //   // app.alert("请选择地理位置");
                  //   that.setData({ loading: 0, disabled: 0 });
                  //   return false;
                  // }
                  var remark = $("#pageCheckout").find("[name='remark']").val();
                  app.post("api/pay/mall_order",{
                    remark: remark,
                    address: JSON.stringify(this.address) ,
                    shop_id:this.shop_id,
                    use_yie: this.use_yie,
                    card_code: this.card_code,
                    location_info: JSON.stringify(this.location_info),
                    delivery_type: this.delivery_type,
                    deliver_time: this.delivery_time.join(",")
                  },function(res){
                    if (res.code != 200) {
                      app.alert(res.msg);
                      that.payloading = 0;
                      that.setData({ 'loading': 0 });
                      that.setData({ 'disabled': 0 });
                      return false;
                    }
                    var order_sn = res.data.order_sn;
                    app.pay(order_sn);
                   
                  });
                },
                moreAct:function(e){
                  var that = this;
                  var itemListArray = [];
                  var goods_id = e.currentTarget.dataset.goods_id;
                  var goods_spec_id = e.currentTarget.dataset.goods_spec_id;
                  
                },
                //选择卡券
                chooseCard:function(){
                  var that = this;
                  app.component("card",{
                     success:function(res){
                        that.$router.go(-1);
                        that.card_code = res.card_code;
                        that.card_title = res.card_title;
                        that.loadCart(1);
                     }
                  });
                }


            }

        }).$mount('#app');
    };
    module.exports = controller;
});
